//
//  CZComposeView.swift
//  weibo
//
//  Created by Apple on 16/3/17.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit
import pop

class CZComposeView: UIView {

    // MARK:    懒加载控件
    private lazy var composeMenuButtonArray = [CZComposeMenuButton]()
    //  目标控制器
    var targetViewController: UIViewController?
    
    //  加载plist文件数据
    var composeArray: NSArray = {
    
        let path = NSBundle.mainBundle().pathForResource("compose", ofType: "plist")
        let composeArray = NSArray(contentsOfFile: path!)!
        return composeArray
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        //  设置当前控件的frame和物理屏幕一样大
        self.frame = UIScreen.mainScreen().bounds
        setupUI()

    }
    
  

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
    
        backgroundColor = RandomColor()
        //  添加控件
        addSubview(bgImageView)
        addSubview(sloganImageview)
        addChildMenuButton()
        //  设置约束
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(UIEdgeInsetsZero)
        }
        sloganImageview.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        }
    }
    // MARK:    懒加载控件
    private lazy var bgImageView: UIImageView = UIImageView(image: UIImage.getScreenShot().applyLightEffect())
    
//    private lazy var menuButton: CZComposeMenuButton = {
//    
//        let button = CZComposeMenuButton()
//        button.size = CGSize(width: 80, height: 110)
//        button.setTitle("文字", forState: .Normal)
//        button.setImage(UIImage(named: "tabbar_compose_friend"), forState: .Normal)
//
//        return button
//        
//    }()
    
    //  宣传语图片
    private lazy var sloganImageview: UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    
    
    private func addChildMenuButton() {
        
        let composeButtonW: CGFloat = 80
        let composeButtonH: CGFloat = 110
        
        let composeButtonMargin = (ScreenWidth - (3 * composeButtonW)) / 4
        
        //  加载plist文件
//        let path = NSBundle.mainBundle().pathForResource("compose", ofType: "plist")
//        let composeArray = NSArray(contentsOfFile: path!)!
        
        for (i, value) in composeArray.enumerate() {
            let button = CZComposeMenuButton()
            button.tag = i
            button.addTarget(self, action: "composeMenuButtonClick:", forControlEvents: .TouchUpInside)
            button.size = CGSize(width: composeButtonW, height: composeButtonH)
            
            let title = value["title"] as! String
            let imgname = value["icon"] as! String
            
            button.setTitle(title, forState: .Normal)
            button.setImage(UIImage(named: imgname), forState: .Normal)
            
            //  遍历到第几行，第几列
            let col = i % 3
            let row = i / 3
            
            button.x = CGFloat(col) * composeButtonW + CGFloat(col + 1) * composeButtonMargin
            button.y = CGFloat(row) * (composeButtonH + composeButtonMargin) + ScreenHight
            
            //  添加到数组中
            composeMenuButtonArray.append(button)
            
            addSubview(button)
        }
        
    }
    
    func show(target: UIViewController) {
//        let window = UIApplication.sharedApplication().windows.last
//        window?.addSubview(self)
        
        self.targetViewController = target
        //  添加到UIMainViewControll的view上，因为添加到window上回挡住我们的弹出控制器
        target.view.addSubview(self)
        for (i,composeMenuButton) in composeMenuButtonArray.enumerate() {
           addComposeMenuButtonAnimation(composeMenuButton, isUP: true, index: i)
        }
        
        
    }
    
    private func addComposeMenuButtonAnimation(button: CZComposeMenuButton, isUP:Bool, index: Int) {

        //  pop的弹簧效果，添加到view
        let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        //  视图移动的中心点位置
        let y = isUP ? button.center.y - 350 : button.center.y + 350
        animation.toValue = NSValue(CGPoint: CGPoint(x: button.center.x, y: y))
        //  弹性效果，数值越大，弹动的效果越大
        animation.springBounciness = 8
        //  弹性速度 数值越大，速度越快
        animation.springSpeed = 10
        print(CACurrentMediaTime())
        //  当前的绝对时间
        animation.beginTime = CACurrentMediaTime() + Double(index) * 0.025
        
        button.pop_addAnimation(animation, forKey: nil)
            

    }
    
    // MARK:   点击事件
    @objc private func composeMenuButtonClick(button: CZComposeMenuButton) {
    
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            
            for value in self.composeMenuButtonArray {
                //  改变透明度
                value.alpha = 0.2
                if value == button {
                    //  放大
                    value.transform = CGAffineTransformMakeScale(2, 2)
                } else {
                
                    //  其它缩小
                    value.transform = CGAffineTransformMakeScale(0.3, 0.3)
                }
            }
            
            
        }) { (_) -> Void in
//            UIView.animateWithDuration(0.25, animations: { () -> Void in
//                for value in self.composeMenuButtonArray {
//                    //  透明度不透明
//                    value.alpha = 1
//                    //  回到原始位置
//                    value.transform = CGAffineTransformIdentity
//                }
//            })
         
            
            //  跳转到其他控制器
            
            if let className = self.composeArray[button.tag]["classname"] as? String {
                let classType = NSClassFromString(className) as! UIViewController.Type
                let vc = classType.init()
                
                //let composeVC = CZComposeViewController()
                //let navComposeVc = UINavigationController(rootViewController: composeVC)
                let navComposeVc = CZNavigationController(rootViewController: vc)
                self.targetViewController?.presentViewController(navComposeVc, animated: true, completion: { () -> Void in
                    //  弹出视图控制器后，移除当前视图
                    self.removeFromSuperview()
                })
            }
            
        }
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

        
        for (i,composeMenuButton) in composeMenuButtonArray.enumerate() {
            addComposeMenuButtonAnimation(composeMenuButton, isUP: false, index: i)
        }
       

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.3 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            self.removeFromSuperview()
        }
       
    }

}
